package com.hjm.project.ShopOrder.ShopOrder.controller;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.hjm.common.exception.BusinessException;
import com.hjm.common.utils.StringUtils;
import com.hjm.common.utils.yh.PoiUtil;
import com.hjm.project.ShopExpress.ShopExpress.domain.ShopExpress;
import com.hjm.project.ShopExpress.ShopExpress.service.IShopExpressService;
import com.hjm.project.ShopOrderBreak.ShopOrderBreak.domain.ShopOrderBreak;
import com.hjm.project.ShopOrderBreak.ShopOrderBreak.service.IShopOrderBreakService;
import com.hjm.project.agentInfo.agentInfo.domain.AgentInfo;
import com.hjm.project.agentInfo.agentInfo.service.IAgentInfoService;
import com.hjm.project.formalPos.branchPos.service.IBranchPosService;
import com.hjm.project.terminal.record.domain.TerminalRecord;
import com.hjm.project.terminal.record.service.ITerminalRecordService;
import org.apache.commons.collections.CollectionUtils;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.transaction.PlatformTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import com.hjm.framework.aspectj.lang.annotation.Log;
import com.hjm.framework.aspectj.lang.enums.BusinessType;
import com.hjm.project.ShopOrder.ShopOrder.domain.ShopOrder;
import com.hjm.project.ShopOrder.ShopOrder.service.IShopOrderService;
import com.hjm.framework.web.controller.BaseController;
import com.hjm.framework.web.domain.AjaxResult;
import com.hjm.common.utils.poi.ExcelUtil;
import com.hjm.framework.web.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;

/**
 * 订单Controller
 * 
 * @author ShopOrder
 * @date 2020-11-30
 */
@Controller
@RequestMapping("/ShopOrder/ShopOrder")
public class ShopOrderController extends BaseController
{
    private String prefix = "ShopOrder/ShopOrder";

    @Autowired
    private IShopOrderService shopOrderService;


    @Autowired
    private PlatformTransactionManager txManager;


    @Autowired
    private IShopOrderBreakService iShopOrderBreakService;

    @Autowired
    private IShopExpressService iShopExpressService;


    @Autowired
    private ITerminalRecordService iTerminalRecordService;

    @Autowired
    private IAgentInfoService agentInfoService;

    @Resource
    private ITerminalRecordService terminalRecordService;

    @Resource
    private IBranchPosService iBranchPosService;


    @RequiresPermissions("ShopOrder:ShopOrder:view")
    @GetMapping()
    public String ShopOrder()
    {
        return prefix + "/ShopOrder";
    }

    /**
     * 查询订单列表
     */
    @RequiresPermissions("ShopOrder:ShopOrder:list")
    @PostMapping("/list")
    @ResponseBody
    public TableDataInfo list(ShopOrder shopOrder)
    {
        startPage();
        List<ShopOrder> list = shopOrderService.selectShopOrderList(shopOrder);
        return getDataTable(list);
    }

    /**
     * 导出订单列表
     */
    @RequiresPermissions("ShopOrder:ShopOrder:export")
    @Log(title = "订单", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    @ResponseBody
    public AjaxResult export(ShopOrder shopOrder)
    {
        List<ShopOrder> list = shopOrderService.selectShopOrderList(shopOrder);
        ExcelUtil<ShopOrder> util = new ExcelUtil<ShopOrder>(ShopOrder.class);
        return util.exportExcel(list, "ShopOrder");
    }

    /**
     * 新增订单
     */
    @GetMapping("/add")
    public String add()
    {
        return prefix + "/add";
    }

    /**
     * 新增保存订单
     */
    @RequiresPermissions("ShopOrder:ShopOrder:add")
    @Log(title = "订单", businessType = BusinessType.INSERT)
    @PostMapping("/add")
    @ResponseBody
    public AjaxResult addSave(ShopOrder shopOrder)
    {
        return toAjax(shopOrderService.insertShopOrder(shopOrder));
    }

    /**
     * 修改订单
     */
    @GetMapping("/edit/{serialLogo}")
    public String edit(@PathVariable("serialLogo") Long serialLogo, ModelMap mmap)
    {
        ShopOrder shopOrder = shopOrderService.selectShopOrderById(serialLogo);
        mmap.put("shopOrder", shopOrder);
        return prefix + "/edit";
    }

    /**
     * 修改保存订单
     */
    @RequiresPermissions("ShopOrder:ShopOrder:edit")
    @Log(title = "订单", businessType = BusinessType.UPDATE)
    @PostMapping("/edit")
    @ResponseBody
    public AjaxResult editSave(ShopOrder shopOrder)
    {
        return toAjax(shopOrderService.updateShopOrder(shopOrder));
    }

    /**
     * 删除订单
     */
    @RequiresPermissions("ShopOrder:ShopOrder:remove")
    @Log(title = "订单", businessType = BusinessType.DELETE)
    @PostMapping( "/remove")
    @ResponseBody
    public AjaxResult remove(String ids)
    {
        return toAjax(shopOrderService.deleteShopOrderByIds(ids));
    }



    /**
     * 获取订单的收货地址
     */
    @Log(title = "获取收货地址", businessType = BusinessType.OTHER)
    @PostMapping( "/getTake")
    @ResponseBody
    public Map getTake(ShopOrder shopOrder){
        shopOrder = shopOrderService.selectShopOrderByIds(shopOrder.getOrderNo());
        HashMap map = new HashMap();
        map.put("data",shopOrder);
        return map;
    }


    @Log(title = "获取物流基础信息", businessType = BusinessType.OTHER)
    @RequestMapping( "/getWlInfo")
    @ResponseBody
    public TableDataInfo getWlInfo(){
        ShopExpress shopExpress = new ShopExpress();
        shopExpress.setStatus(Long.parseLong("1"));
        return getDataTable(iShopExpressService.selectShopExpressList(shopExpress));
    }



    /**
     * 订单发货
     */
    @Log(title = "订单发货", businessType = BusinessType.OTHER)
    @PostMapping( "/delivery")
    @ResponseBody
    public AjaxResult delivery(ShopOrderBreak orderBreak, MultipartFile file, String startSn, TerminalRecord record) throws Exception {
        if ("选择快递".equals(orderBreak.getExpressId())) {
            throw  new BusinessException("请选择快递公司");
        } else  if (StringUtils.isEmpty(orderBreak.getExpressOrderNo())){
            throw  new BusinessException("快递单号不能为空");
        } else if (orderBreak.getExpressOrderNo().length() < 10){
            throw  new BusinessException("请输入正确的快递单号");
        }
        DefaultTransactionDefinition def = new DefaultTransactionDefinition();
        def.setPropagationBehavior(TransactionDefinition.PROPAGATION_REQUIRED);
        TransactionStatus status = txManager.getTransaction(def);
        //设置目标划拨服务商
        record.setAgentTarNum(orderBreak.getAgentNum());
        AgentInfo agentInfo = agentInfoService.selectAgentInfoByAgentNum(orderBreak.getAgentNum());
        record.setAgentTarName(agentInfo.getAgentName());
        try {
            //发货操作(返回当前订单的终端数量)
            int goodsNums = shopOrderService.delivery(orderBreak);
            //划拨操作
            //如果是文件
            if (orderBreak.getHbType().equals("2")) {
                if (file == null) {
                    throw  new BusinessException("请上传终端Excel文件");

                }
                    if (file.getSize() == 0) {
                    throw  new BusinessException("请上传正确的终端Excel文件");

                }


                File files = File.createTempFile("prefix", "_" + file.getOriginalFilename());
                file.transferTo(files);
                Map<String, Map<String, Object>> lines = PoiUtil.readExcelContent(files.getPath());
                if (lines.size() != goodsNums) {
                    throw  new BusinessException("订单机具数量与导入文件机具编号不一致，请检查后重新选择");
                }
                List<String> posNo = new ArrayList<>();
                for (Map ss : lines.values()) {
                    String tempPosNo = ss.values().toString().replace("[","").replace("]","");
                    String no=terminalRecordService.getPosNoNum(tempPosNo);
                    if (StringUtils.isEmpty(no)) {
                        throw  new BusinessException("SN号不存在,请核对SN数据");
                    }
                    posNo.add(no);
                }
                Map<String, String> result = iTerminalRecordService.insertTerminalRecord(record, posNo, orderBreak.getOrderNo());
                if (!result.get("code").equals("00")) {
                    throw new BusinessException(result.get("msg"));
                }

            }
            //SN划入
            if (orderBreak.getHbType().equals("1")) {
                //如果是SN号段 默认每次累加1
                List<String> posNo = new ArrayList<>();
                //机具编号前部分
                String startOne = startSn.substring(0, 9);
                Integer start = Integer.parseInt(startSn.substring(9, startSn.length()));
                Integer end = start + goodsNums;
                for (int i = start; i < end; i++) {
                    String no=terminalRecordService.getPosNoNum(startOne+i);
                    if (StringUtils.isEmpty(no)) {
                        throw  new BusinessException("SN号不存在,请核对SN数据");
                    }
                    posNo.add(no);
                }
                //数量不符合说明是错误数据
                if (CollectionUtils.isEmpty(posNo) || posNo.size() != goodsNums ) {
                    throw  new BusinessException("订单终端数量和SN号段数量不符合,请重试");
                }
                Map<String, String> result = iTerminalRecordService.insertTerminalRecordSn(record, posNo, orderBreak.getOrderNo());
                if (!result.get("code").equals("00")) {
                    throw new BusinessException(result.get("msg"));
                }

            }
            //划拨成功后更新订单划拨状态
            ShopOrder shopOrder = new ShopOrder();
            shopOrder.setHbRecord(1);
            shopOrder.setOrderNo(orderBreak.getOrderNo());
            shopOrderService.updateShopOrder(shopOrder);

         /*   //插入NORM_NUM指标数，除100取整数
            BigDecimal fileSize=new BigDecimal(goodsNums);
            BigDecimal count=new BigDecimal("100");
            BigDecimal subCount =  fileSize.divide(count,BigDecimal.ROUND_DOWN);
            agentInfo.setNorm_num(subCount.longValue());
            agentInfoService.updateAgentNorm(agentInfo);*/

        } catch (Exception ex) {
            txManager.rollback(status);
            throw ex;
        }
        txManager.commit(status);
        return AjaxResult.success("发货并划拨成功");
    }



    @Log(title = "获取物流", businessType = BusinessType.OTHER)
    @GetMapping( "/queryOrderView")
    public String queryOrderView(ShopOrder order,ModelMap mmp){
        mmp.put("orderNo",order.getOrderNo());
        ShopOrderBreak sob = new ShopOrderBreak();
        sob.setOrderNo(order.getOrderNo());
        ShopOrder shopOrder = shopOrderService.selectShopOrderByIds(order.getOrderNo());
        //订单基本信息
        mmp.put("shopOrder",shopOrder);
        List<ShopOrderBreak> shopOrderBreaks = iShopOrderBreakService.selectShopOrderBreakList(sob);
        if (CollectionUtils.isNotEmpty(shopOrderBreaks)) {
            mmp.put("expressName",shopOrderBreaks.get(0).getExpressName());
            mmp.put("expressOrderNo",shopOrderBreaks.get(0).getExpressOrderNo());
        }
        return prefix + "/queryOrderView";
    }


    /**
     * 获取物流
     */
    @Log(title = "获取物流", businessType = BusinessType.OTHER)
    @PostMapping( "/getDelivery")
    @ResponseBody
    public TableDataInfo getDelivery(ShopOrderBreak orderBreak){
        return getDataTable(shopOrderService.queryOrder(orderBreak));
    }
}
